﻿using System;
using System.Collections.Concurrent;
using ePipe;
using System.Runtime.CompilerServices;
using System.Threading;

namespace Letter.Net.Sockets;

abstract class ASocketSnderPool<TSnder>: ASocketSnderProvider<TSnder> where TSnder : ASocketSnder
{
    private const int MaxQueueSize = 1024; // REVIEW: Is this good enough?

    private readonly ConcurrentQueue<TSnder> _queue = new();
    private int _count;
    private bool _disposed;

    public ASocketSnderPool(PipeScheduler scheduler) : base(scheduler)
    {
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public override TSnder Rent()
    {
        if (_queue.TryDequeue(out var sender))
        {
            Interlocked.Decrement(ref _count);
            return sender;
        }
        return Create(this.Scheduler);
    }
    
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public override void Return(TSnder sender)
    {
        // This counting isn't accurate, but it's good enough for what we need to avoid using _queue.Count which could be expensive
        if (_disposed || Interlocked.Increment(ref _count) > MaxQueueSize)
        {
            Interlocked.Decrement(ref _count);
            sender.Dispose();
            return;
        }

        sender.Reset();
        _queue.Enqueue(sender);
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public override void Dispose()
    {
        if (!_disposed)
        {
            _disposed = true;
            while (_queue.TryDequeue(out var sender))
            {
                sender.Dispose();
            }

            base.Dispose();
        }
    }
}